<template>
  <div class="app-container">
    <el-form :model="searchForm" ref="searchFormRef" size="small" inline v-show="showSearch">
      <el-form-item label="地区名称" prop="like.name">
        <el-input v-model="searchForm.like.name" placeholder="请输入地区名称" clearable @keyup.enter="search"/>
      </el-form-item>
      <el-form-item label="状态" prop="where.status">
        <el-select v-model="searchForm.where.status" placeholder="状态" clearable class="w-120px">
          <el-option
            v-for="dict in dict.type.sys_show_hide"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="mb-8px reset">
      <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" v-hasPerm="['system:city:add']">新增省份</el-button>
      <el-button type="info" plain icon="el-icon-sort" @click="handleExpand">展开/折叠</el-button>
      <right-toolbar :showSearch.sync="showSearch" @refresh="getList"/>
    </div>
    <el-table v-if="refreshTable" v-loading="loading" :data="listData" row-key="id" :default-expand-all="isExpandAll" lazy :load="loadChildren">
      <el-table-column prop="name" label="地区名称" min-width="160" />
      <el-table-column align="center" prop="area_code" label="区号" min-width="80" />
      <el-table-column align="center" prop="short_name" label="简称" min-width="90" />
      <el-table-column align="center" prop="merge_name" label="组合名称" min-width="90" />
      <el-table-column label="中心坐标" align="center" min-width="100">
        <template v-slot="{ row }">{{ row.lng }},{{ row.lat }}</template>
      </el-table-column>
      <el-table-column align="center" prop="status" label="状态" min-width="80">
        <template v-slot="{ row }">
          <dict-tag :options="dict.type.sys_show_hide" :value="row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="150">
        <template v-slot="{ row }">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(row)" v-hasPerm="['system:city:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(row)" v-hasPerm="['system:city:add']" v-if="row.level < 2">新增</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(row)" v-hasPerm="['system:city:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <city-form v-model="formShow" :module-name="moduleName" :row="formData" @submit="formSubmit" v-if="formShow"/>
  </div>
</template>

<script>
import { listCityApi, delCityApi } from '@/api/system/city'
import CityForm from './form.vue'

export default {
  name: 'City',
  dicts: ['sys_show_hide'],
  components: { CityForm },
  data() {
    return {
      moduleName: '地区',
      formData: null,
      formShow: false,
      loading: true,
      showSearch: true,
      listData: [],
      isExpandAll: false,
      refreshTable: true,
      searchForm: {
        like: { name: undefined },
        where: { status: undefined, parent_id: 0 },
        isTotal: 1
      },
      loadNode: new Map()
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listCityApi(this.searchForm).then(res => {
        let list = res?.list || []
        list = list.map(item => {
          item.hasChildren = true
          return item
        })
        this.listData = list
        this.loading = false
      })
    },
    // 加载子节点，
    loadChildren(tree, treeNode, resolve) {
      let searchParams = this.deepClone(this.searchForm)
      searchParams.where.parent_id = tree.id
      listCityApi(searchParams).then(res => {
        let list = res?.list || []
        if (tree.level < 1) {
          list = list.map(item => {
            item.hasChildren = true
            return item
          })
        }
        this.loadNode.set(tree.id, { tree, treeNode, resolve })
        resolve(list)
      })
    },
    // 修改添加删除后刷新列表，需要重新加载父级节点
    formSubmit() {
      if (this.formData.parent_id && this.loadNode.get(this.formData.parent_id)) {
        const { tree, treeNode, resolve } = this.loadNode.get(this.formData.parent_id)
        if (tree) this.loadChildren(tree, treeNode, resolve)
      } else {
        this.getList()
      }
    },
    search() {
      this.getList()
    },
    reset() {
      this.resetForm('searchFormRef')
      this.search()
    },
    handleExpand() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    handleAdd(row) {
      this.formData = { parent_id: row.id || 0, parent_name: row?.name || '' }
      this.formShow = true
    },
    handleEdit(row) {
      const editId = row?.id || 0
      if (!editId) return this.$modal.msgError('参数缺失')
      this.formData = { id: editId, parent_id: row?.parent_id || 0 }
      this.formShow = true
    },
    handleDelete(row) {
      const delIds = row?.id || ''
      if (!delIds) return this.$modal.msgWarning('未选择数据')
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(() => {
        return delCityApi(delIds)
      }).then((res) => {
        this.formData = { parent_id: row?.parent_id || 0 }
        this.formSubmit()
        this.$modal.msgSuccess(res?.msg || '删除成功')
      }).catch(() => {})
    }
  }
}
</script>
